import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import api, { API_URLS } from '../utils/api';

// 用户角色枚举 - 与后端匹配
export enum UserRole {
  SUPER_ADMIN = 'SUPER_ADMIN',
  ADMIN = 'ADMIN',
  USER = 'USER'
}

// 用户接口
export interface User {
  id: string;
  email: string;
  username?: string;
  password_hash: string;
  is_active: boolean;  // 用于标识用户状态（激活/VIP）
  role: UserRole;
  created_at: string;
  updated_at: string;
  phone?: string;
  last_login?: string;
  is_admin: boolean;
}

interface AuthContextType {
  isAuthenticated: boolean;
  user: User | null;
  loading: boolean;
  login: (email: string, password?: string, code?: string) => Promise<void>;
  logout: () => void;
  register: (email: string, password: string, username: string) => Promise<void>;
  hasPermission: (requiredRole: UserRole) => boolean;
  canManageUser: (targetUserRole: UserRole) => boolean;
  setUser: (user: User | null) => void;
  setIsAuthenticated: (isAuthenticated: boolean) => void;
}

// 注册数据接口
interface RegisterData {
  username: string;
  password: string;
  phone?: string; 
  email?: string;
}

const defaultValue: AuthContextType = {
  isAuthenticated: false,
  user: null,
  loading: true,
  login: async () => {},
  logout: () => {},
  register: async () => {},
  hasPermission: () => false,
  canManageUser: () => false,
  setUser: () => {},
  setIsAuthenticated: () => {},
};

const AuthContext = createContext<AuthContextType>(defaultValue);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    // 检查本地存储中是否有令牌
    const checkAuth = async () => {
      const token = localStorage.getItem('token');
      if (token) {
        try {
          // 获取用户信息
          const response = await api.get(API_URLS.CURRENT_USER);
          setUser(response.data);
          setIsAuthenticated(true);
        } catch (error) {
          // 令牌无效，清除它
          localStorage.removeItem('token');
          setUser(null);
          setIsAuthenticated(false);
        }
      }
      setLoading(false);
    };

    checkAuth();
  }, []);

  const login = async (email: string, password?: string, code?: string) => {
    try {
      setLoading(true);
      
      const response = await api.post(API_URLS.LOGIN, {
        email,
        ...(password ? { password } : {}),
        ...(code ? { code } : {})
      });
      
      const { user, token } = response.data;
      
      // 保存token到localStorage
      if (token) {
        localStorage.setItem('token', token);
      }
      
      // 设置用户信息
      setUser({
        id: user.id,
        email: user.email,
        username: user.username,
        role: user.is_admin ? UserRole.ADMIN : UserRole.USER,
        is_active: true,
        password_hash: '',
        created_at: '',
        updated_at: '',
        is_admin: user.is_admin
      });
      setIsAuthenticated(true);
    } catch (error: any) {
      // 清除任何可能存在的旧状态
      localStorage.removeItem('token');
      setUser(null);
      setIsAuthenticated(false);
      
      // 重新抛出错误，让调用者处理
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const logout = async () => {
    // 清除令牌和状态
    localStorage.removeItem('token');
    setUser(null);
    setIsAuthenticated(false);
  };

  // 注册新用户
  const register = async (email: string, password: string, username: string) => {
    try {
      const response = await api.post('/users/register', {
        email,
        password,
        username
      });
      return response.data;
    } catch (error: any) {
      throw new Error(error.response?.data?.detail || '注册失败');
    }
  };

  // 检查用户是否具有特定权限
  const hasPermission = (requiredRole: UserRole): boolean => {
    if (!user) return false;
    
    switch (user.role) {
      case UserRole.SUPER_ADMIN:
        // 超级管理员拥有所有权限
        return true;
      case UserRole.ADMIN:
        // 管理员拥有除了超级管理员的全部权限
        return requiredRole !== UserRole.SUPER_ADMIN;
      case UserRole.USER:
        // 普通用户只能访问用户权限
        return requiredRole === UserRole.USER;
      default:
        return false;
    }
  };

  // 检查当前用户是否可以管理目标用户
  const canManageUser = (targetUserRole: UserRole): boolean => {
    if (!user) return false;
    
    // 超级管理员可以管理所有用户
    if (user.role === UserRole.SUPER_ADMIN) return true;
    
    // 管理员可以管理普通用户，但不能管理超级管理员或其他管理员
    if (user.role === UserRole.ADMIN) {
      return targetUserRole === UserRole.USER;
    }
    
    // 普通用户不能管理任何人
    return false;
  };

  return (
    <AuthContext.Provider
      value={{
        isAuthenticated,
        user,
        loading,
        login,
        logout,
        register,
        hasPermission,
        canManageUser,
        setUser,
        setIsAuthenticated
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}; 